﻿using System;
using System.Collections.Generic;
using ConsoleCommand.Commands;

namespace ConsoleCommand.Utilities
{
    class ParameterParser
    {
        static public IDictionary<CommandParameter, string> Parse(string[] args) {
            string command = null;
            Dictionary<string, string> switches = new Dictionary<string, string>();
            string currentSwitch=null;
            foreach(string arg in args){
                if(arg.StartsWith("/")||arg.StartsWith("-")){
                    int switchEnd=arg.IndexOfAny(new char[]{':','=',' '});
                    if(switchEnd>-1&&switchEnd<arg.Length-1){
                        currentSwitch=arg.Substring(1,switchEnd-1);
                        if(currentSwitch!=null)switches.Add(currentSwitch,arg.Substring(switchEnd+1));
                        continue;
                    }
                    currentSwitch=arg.TrimStart('/', '-').TrimEnd(':','=',' ');
                    if(currentSwitch!=null)switches.Add(currentSwitch,null);
                }else{
                    if(currentSwitch!=null){
                        switches[currentSwitch]=arg;
                        currentSwitch=null;
                    }else{
                        if(String.IsNullOrEmpty(command))command=arg;
                    }
                }
            }

            Dictionary<CommandParameter,string> parameters=new Dictionary<CommandParameter,string>(){
                {CommandParameter.Command,command}
            };
            foreach (KeyValuePair<string, string> pair in switches){
                try{
                    CommandParameter parameter=(CommandParameter)Enum.Parse(typeof(CommandParameter), pair.Key, true);
                    parameters[parameter]=pair.Value;
                }catch(ArgumentException){}
            }
            return parameters;
        }
    }
}
